<template>
  <div class="password-container">
    <h2 class="title">修改密码</h2>
    <el-form
        ref="form"
        :model="formData"
        :rules="rules"
        label-width="100px"
        class="password-form"
    >
      <el-form-item label="原密码" prop="oldPassword">
        <el-input
            v-model="formData.oldPassword"
            type="password"
            show-password
            placeholder="请输入原密码"
        />
      </el-form-item>

      <el-form-item label="新密码" prop="newPassword">
        <el-input
            v-model="formData.newPassword"
            type="password"
            show-password
            placeholder="请输入新密码（至少6位）"
        />
      </el-form-item>

      <el-form-item label="确认密码" prop="confirmPassword">
        <el-input
            v-model="formData.confirmPassword"
            type="password"
            show-password
            placeholder="请再次输入新密码"
        />
      </el-form-item>

      <el-form-item>
        <el-button
            type="primary"
            @click="submitForm"
            :loading="submitting"
        >
          提交修改
        </el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import {updatePersonInfo, validatePwd} from "@/api/request/WebRequest";

export default {
  name: "UpdatePassword",
  data() {
    const validateConfirm = (rule, value, callback) => {
      if (value !== this.formData.newPassword) {
        callback(new Error('两次输入密码不一致'));
      } else {
        callback();
      }
    };

    const validate = (rule, value, callback) => {
      validatePwd({id: this.userInfo.id, password: value}).then(res => {
        if (res.code !== 200) {
          callback(new Error('原密码错误'));
        } else {
          callback();
        }
      }).catch(error => {
        console.log(error)
      });
    }

    return {
      submitting: false,
      userInfo: {},
      formData: {
        oldPassword: '',
        newPassword: '',
        confirmPassword: ''
      },
      rules: {
        oldPassword: [
          {required: true, message: '请输入原密码', trigger: 'blur'},
          {validator: validate, trigger: 'blur'}
        ],
        newPassword: [
          {required: true, message: '请输入新密码', trigger: 'blur'},
          {min: 6, message: '密码长度至少6位', trigger: 'blur'}
        ],
        confirmPassword: [
          {required: true, message: '请确认新密码', trigger: 'blur'},
          {validator: validateConfirm, trigger: 'blur'}
        ]
      }
    };
  },
  methods: {
    submitForm() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          updatePersonInfo({id: this.userInfo.id, password: this.formData.confirmPassword}).then(res => {
            if (res.code !== 200) {
              this.$message.error(res.msg);
              return;
            }

            this.$message.success('修改成功请重新登录');
            localStorage.removeItem('xm-user')

            setTimeout(() => {
              this.$router.push('/Login')
              window.location.reload(true);
            }, 500)
          }).catch(error => {
            console.log(error)
          });
        }
      })
    },
  },
  mounted() {
    this.userInfo = JSON.parse(localStorage.getItem('xm-user'))
  }
};
</script>

<style scoped lang="scss">
.password-container {
  max-width: 500px;
  margin: 20px auto;
  padding: 20px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);

  .title {
    text-align: center;
    margin-bottom: 30px;
  }

  .password-form {
    ::v-deep .el-form-item__content {
      line-height: normal;
    }
  }
}
</style>
